
<!-- 低代码 主页面：用于编辑详情页  eui-page-frame-->

<template>
  <eui-background type="common" >
    <view class="lowcode-nav-wrap">
      <eui-nav-bar :title="state?.pageTitle" color="#333"  />
      <eui-search-bar v-if="lowcodePage?.Search?.SearchItems?.length" ref="searcBarRef" radius="100" showFilter placeholder="请输入搜索内容" @clear="handleClearSearch" @confirm="handleEnterSearch" >
        <template #searchFields>
          <view class="lowcode-components-wrap">
            <view v-for="(colField, idx) in lowcodePage?.Search?.SearchItems" :key="idx" class="lowcode-components-item">
              <DynamicComponent :conf-object="colField" :data-object="state.searchCardData" parentSrc="1" @handleDynamicChange="handleSearchDynamicChange" :md-code="state.mdCode || ''" />
            </view>
          </view>
          <view class="lowcode-popup-bottom flex-1 flex">
            <eui-button type="max2" title="重置" singleTag="重置" @buttonClick="handlePopupClose"></eui-button>
            <eui-button type="max" title="确认" singleTag="确认" @buttonClick="handlePopupClose"></eui-button>
          </view>
        </template>
      </eui-search-bar>
    </view>
    <view class="lowcode-query-wrap" :style="state?.cntStyle">
      <view v-for="(oPanelGridGuid, pIdx) in Object.keys(state.PanelGridObj || {})" :key="pIdx" class="lowcode-query-panel-grid-wrap">
        <eui-card v-if="(state?.PanelGridObj?.[oPanelGridGuid]?.c_type === '3' && state?.PanelGridObj?.[oPanelGridGuid]?.Components?.length)" :title="state?.PanelGridObj?.[oPanelGridGuid]?.c_name" hPadding="28" type="single" >
          <view class="lowcode-title-line" />
          <view  v-for="(rowData, idx) in (state.PanelData?.[oPanelGridGuid])" :key="idx" class="lowcode-edit-page-tb-row-wrap" >
            <view class="lowcode-edit-page-tb-row-title">第{{ (+idx || 0) + 1 }}行</view>
            <view class="lowcode-page-card-chead-wrap" v-if="state?.PanelGridObj?.[oPanelGridGuid]?.ComponentsHeade?.length" >
              <eui-row v-for="(rowCols, fIdx) in state?.PanelGridObj?.[oPanelGridGuid]?.ComponentsHeade" :key="fIdx" class="lowcode-page-row-wrap">
                <eui-col v-for="(colField, cfIdx) in rowCols" :key="cfIdx" class="lowcode-page-col" :span="colField?.c_col_span || 12">
                  <view class="lowcode-item-detail-view" >
                    <text class="lowcode-card-title item-text item-text-detail">{{ getDetailCardTitle(rowData, colField) }}</text>
                  </view>
                </eui-col>
              </eui-row>
            </view>
            <view class="lowcode-title-line" v-if="state?.PanelGridObj?.[oPanelGridGuid]?.ComponentsHeade?.length" />
            <view class="lowcode-page-card-cnt" v-if="state?.PanelGridObj?.[oPanelGridGuid]?.Components?.length">
              <eui-row v-for="(rowCols, fIdx) in state?.PanelGridObj?.[oPanelGridGuid]?.Components" :key="fIdx" class="lowcode-page-row-wrap">
                <eui-col v-for="(colField, cfIdx) in rowCols" :key="cfIdx" class="lowcode-page-col" :span="colField?.c_col_span || 12">
                  <eui-text v-if="colField?.c_type !== 'fileupload'" cWidth="width: 100%" v-bind="state.PanelCellProps?.[oPanelGridGuid+'_'+idx+'_'+fIdx+'_'+cfIdx]" />
                  <UploadFile v-else-if="colField?.c_type === 'fileupload'" :readonly="true" :autoUpload="false" serviceName="EnjoyMain" fileMediatype="image" :fileId="rowData?.[colField?.c_code || '']" fileClass="lowcode"
                    return-type="array" mode="grid" :imageStyles="{ width:74,height:74 }" :customFetchUniqueKey="LOWCODERUNTIMEUNIQUEKEY" customFetchMethodName="FetchLowcodeFile" />
                </eui-col>
              </eui-row>
            </view>
          </view>
          <view class="lowcode-page-sub-card-panel" v-for="(otherSubCardFormPanel, pIdx) in state?.subPanelsGridObj?.[oPanelGridGuid]">
            <view class="lowcode-page-sub-card-chead-wrap" v-if="otherSubCardFormPanel?.c_name" >
              <text class="lowcode-card-title item-text item-text-detail">{{ otherSubCardFormPanel?.c_name }}</text>
            </view>
            <view class="lowcode-title-line" v-if="otherSubCardFormPanel?.c_name" />
            <view class="lowcode-page-sub-card-cnt" v-if="otherSubCardFormPanel?.Components?.length">
              <eui-row v-for="(rowCols, fIdx) in otherSubCardFormPanel?.Components" :key="fIdx" class="lowcode-page-row-wrap">
                <eui-col v-for="(colField, cfIdx) in rowCols" :key="cfIdx" class="lowcode-page-col" :span="colField?.c_col_span || 12">
                  <eui-text v-if="colField?.c_type !== 'fileupload'" cWidth="width: 100%" v-bind="state.subCellProps?.['other_sub'+(otherSubCardFormPanel?.c_guid || '')+idx+'_'+fIdx+'_'+cfIdx]" />
                  <UploadFile v-else-if="colField?.c_type === 'fileupload'" :readonly="true" :autoUpload="false" serviceName="EnjoyMain" fileMediatype="image" :fileId="rowData?.[colField?.c_code || '']" fileClass="lowcode"
                    return-type="array" mode="grid" :imageStyles="{ width:74,height:74 }" :customFetchUniqueKey="LOWCODERUNTIMEUNIQUEKEY" customFetchMethodName="FetchLowcodeFile" />
                </eui-col>
              </eui-row>
            </view>
          </view>
        </eui-card>
        <eui-card v-if="(['1', '2'].includes(state?.PanelGridObj?.[oPanelGridGuid]?.c_type || '') && state?.PanelGridObj?.[oPanelGridGuid]?.Components?.length)" :title="state?.PanelGridObj?.[oPanelGridGuid]?.c_name" hPadding="28" type="single" >
          <view class="lowcode-page-card-chead-wrap" v-if="state?.PanelGridObj?.[oPanelGridGuid]?.ComponentsHeade?.length" >
            <eui-row v-for="(rowCols, fIdx) in state?.PanelGridObj?.[oPanelGridGuid]?.ComponentsHeade" :key="fIdx" class="lowcode-page-row-wrap">
              <eui-col v-for="(colField, cfIdx) in rowCols" :key="cfIdx" class="lowcode-page-col" :span="colField?.c_col_span || 12">
                <view class="lowcode-item-detail-view" >
                  <text class="lowcode-card-title item-text item-text-detail">{{ getDetailCardTitle(state.PanelData?.[oPanelGridGuid], colField) }}</text>
                </view>
              </eui-col>
            </eui-row>
          </view>
          <view class="lowcode-title-line" v-if="state?.PanelGridObj?.[oPanelGridGuid]?.ComponentsHeade?.length" />
          <view class="lowcode-page-card-cnt" v-if="state?.PanelGridObj?.[oPanelGridGuid]?.Components?.length">
            <eui-row v-for="(rowCols, fIdx) in state?.PanelGridObj?.[oPanelGridGuid]?.Components" :key="fIdx" class="lowcode-page-row-wrap">
              <eui-col v-for="(colField, cfIdx) in rowCols" :key="cfIdx" class="lowcode-page-col" :span="colField?.c_col_span || 12">
                <eui-text v-if="colField?.c_type !== 'fileupload'" cWidth="width: 100%" v-bind="state.PanelCellProps?.[oPanelGridGuid+'_form_'+fIdx+'_'+cfIdx]" />
                <UploadFile v-else-if="colField?.c_type === 'fileupload'" :readonly="true" :autoUpload="false" serviceName="EnjoyMain" fileMediatype="image" :fileId="state.PanelData?.[oPanelGridGuid]?.[colField?.c_code || '']" fileClass="lowcode"
                  return-type="array" mode="grid" :imageStyles="{ width:74,height:74 }" :customFetchUniqueKey="LOWCODERUNTIMEUNIQUEKEY" customFetchMethodName="FetchLowcodeFile" />
              </eui-col>
            </eui-row>
          </view>
          <view class="lowcode-page-sub-card-panel" v-for="(otherSubCardFormPanel, pIdx) in state?.subPanelsGridObj?.[oPanelGridGuid]">
            <view class="lowcode-page-sub-card-chead-wrap" v-if="otherSubCardFormPanel?.c_name" >
              <text class="lowcode-card-title item-text item-text-detail">{{ otherSubCardFormPanel?.c_name }}</text>
            </view>
            <view class="lowcode-title-line" v-if="otherSubCardFormPanel?.c_name" />
            <view class="lowcode-page-sub-card-cnt" v-if="otherSubCardFormPanel?.Components?.length">
              <eui-row v-for="(rowCols, fIdx) in otherSubCardFormPanel?.Components" :key="fIdx" class="lowcode-page-row-wrap">
                <eui-col v-for="(colField, cfIdx) in rowCols" :key="cfIdx" class="lowcode-page-col" :span="colField?.c_col_span || 12">
                  <eui-text v-if="colField?.c_type !== 'fileupload'" cWidth="width: 100%" v-bind="state.subCellProps?.['other_sub'+(otherSubCardFormPanel?.c_guid || '')+'form_'+fIdx+'_'+cfIdx]" />
                  <UploadFile v-else-if="colField?.c_type === 'fileupload'" :readonly="true" :autoUpload="false" serviceName="EnjoyMain" fileMediatype="image" :fileId="state.PanelData?.[oPanelGridGuid]?.[colField?.c_code || '']" fileClass="lowcode"
                    return-type="array" mode="grid" :imageStyles="{ width:74,height:74 }" :customFetchUniqueKey="LOWCODERUNTIMEUNIQUEKEY" customFetchMethodName="FetchLowcodeFile" />
                </eui-col>
              </eui-row>
            </view>
          </view>
        </eui-card>
      </view>
    </view>
  </eui-background>
</template>

<script setup lang="ts" >
import { ref } from "vue";
import { onLoad, onReady, onShow } from "@dcloudio/uni-app";

import store from "@/store";
import serviceTools from '@/common/service';
import useService from "@/hooks/useService";
import { initRdsDict, getRdsSysConfig } from "@/hooks/init";
import UploadFile from "@/components/UploadFile.vue";

import DynamicComponent from "../dynamicComponent/index.vue";
import useLowcodeSystemInfo from "../hooks/useSystemInfo";
import type { LowcodeBtnEvent, LowcodeGridRowColComponents, LowcodeMenuItemCFG, LowcodePage, LowcodePagePanel, LowcodePagePanelComponentItem, LowcodeRect, LowCodeWhereListItem } from "../interface";
import { EBillApproveStatus, EBillStatus, ECBillApproveStatus, ECBillStatus, lowcodeDebounceTime, lowcodeRowKey, LOWCODERUNTIMEMOBILEUNIQUEKEY, LOWCODERUNTIMEUNIQUEKEY, LOWCODEUNIQUEKEY } from "../constant";
import type { MdCustomQueryState, MdCustomQueryProps, FetchCustomQueryProxy, LowcodeDYParamItem } from "./interface";
import useComponentProps from "../hooks/useComponentProps";
import { formGridSort, lowcodeDebounce } from "../utils";

const props = defineProps<MdCustomQueryProps>();
const service = useService({ prefix: "mainApi" });
const state = ref<MdCustomQueryState>({}), searcBarRef = ref(null);
const { getSystemInfo } = useLowcodeSystemInfo();
const { getComponentProps } = useComponentProps();

const fetchQueryData = async () => {
  uni.showLoading({ title: "查询中...", mask: true});

  const DYParamItemsReq = state.value.DYParamItems, fetchReqProxy = { ModuleCode: state.value?.mdCode };
  for (let fetchIdx = 0; fetchIdx < (props?.lowcodePage?.Panels?.length || 0); fetchIdx++) {
    const panelInfo = props?.lowcodePage?.Panels?.[fetchIdx];
    if (!panelInfo) {
      continue;
    }
    const pGuid = panelInfo?.c_guid || "";
    const fetchReq = { PanelGuid: pGuid, DYParamItems: DYParamItemsReq }, isForm = ["1", "2"].includes(panelInfo?.c_type || "");
    const fetchMethod = isForm ? "FetchDYRow" : "FetchDYRows";
	  const fetchRes = await service.request(LOWCODERUNTIMEUNIQUEKEY, fetchMethod, fetchReq, "", "", fetchReqProxy);
    if (!state.value.PanelData) {
      state.value.PanelData = {};
    }
    if (fetchRes) {
      state.value.PanelData[pGuid] = fetchRes;
    }
  }
  uni.hideLoading();
  await initData();
};

const getDetailCardTitle = (rowData: any, colField: LowcodePagePanelComponentItem) => {
	const rawIdVal = rowData?.[colField?.c_code || ""];
	if (colField?.c_displayname_code) {
		const rawIdNameVal = rowData?.[colField?.c_displayname_code] || "";
		return rawIdVal ? `[${rawIdVal}]${rawIdNameVal || ""}` : rawIdVal;
	}
	return rawIdVal;
};

const generateWhere = () => {
	let newDYParamItems: LowcodeDYParamItem[] = [];
	const searchVal = state.value.fuzzyVal;
	// const fuzzyFields = props?.lowcodePage?.Search?.c_fuzzyquery?.split(",");
	// Array.isArray(fuzzyFields) && searchVal && fuzzyFields?.forEach((fk, idx) => {
	// 	newDYParamItems.push({ ParamName: fk, ParamValue: searchVal });
	// });
	
	Array.isArray(props?.lowcodePage?.Search?.SearchItems) && props?.lowcodePage?.Search?.SearchItems?.forEach(item => {
    const iCode = item.c_code || "";
		const iVal = state.value.searchCardData?.[iCode] || "";
		newDYParamItems.push({ ParamName: item?.c_code || "", ParamValue: iVal || searchVal || "" });
	});
	state.value.DYParamItems = newDYParamItems;
	uni.showLoading({ title: "查询中...", mask: true});
};

const handleEnterSearch = async (proxy?: { value?: string }) => {
	const searchVal = proxy?.value || "";
	state.value.fuzzyVal = searchVal;
	generateWhere();
	await fetchQueryData()
};

const handleClearSearch = async () => {
	state.value.fuzzyVal = "";
	generateWhere();
	await fetchQueryData()
};

const handleSearchDynamicChange = async (key: string, newVal: any, oldVal: any, proxy?: { [key: string]: any }) => {
	if (!state.value.searchCardData) {
		state.value.searchCardData = {};
	}
	state.value.searchCardData[key] = newVal;
};

const handlePopupClose = async ({ singleTag }) => {
	if (singleTag === "重置") {
		if (!state.value.searchCardData) {
			state.value.searchCardData = {};
		}
		Array.isArray(props?.lowcodePage?.Search?.SearchItems) && props?.lowcodePage?.Search?.SearchItems?.forEach(item => state.value.searchCardData[item.c_code || ""] = "");
	}
	if (singleTag === "确认") {
		generateWhere();
		await fetchQueryData()
		searcBarRef.value?.closeDrawer?.();
	}
};

const fillOtherCellProps = async (pGridInfo: LowcodeGridRowColComponents, pGuid: string, prefix: string, allData: { [key: string]: any }) => {
  if (!pGridInfo || !pGridInfo?.Components) {
    return;
  }
  for (let fIdx = 0; fIdx < pGridInfo?.Components?.length; fIdx++) {
    const rowCols = pGridInfo?.Components[fIdx];
    for (let cfIdx = 0; cfIdx < rowCols?.length; cfIdx++) {
      if (!state.value?.PanelCellProps) {
        state.value.PanelCellProps = {};
      }
      const colField = rowCols[cfIdx];
      state.value.PanelCellProps[prefix+'_'+fIdx+'_'+cfIdx] = await getComponentProps({ componentType: 'EuiText', confObject: colField, dataObject: allData, parentSrc: "3" });
    }
  }
};

const getOtherCellProps = async () => {
  const PanelGuidAry = Object.keys(state.value?.PanelGridObj || {});
	if (!PanelGuidAry?.length) {
		return;
	}
  for (let pidx = 0; pidx < PanelGuidAry.length; pidx++) {
    const pGuid = PanelGuidAry[pidx];
    const guidPanelData = state.value.PanelData?.[pGuid];
    const pGridInfo = state.value?.PanelGridObj?.[pGuid];

    if (!pGridInfo || !pGridInfo?.Components) {
      continue;
    }

    if (["1", "2"].includes(pGridInfo?.c_type || "")) {   // 容器类型，1:普通表单、2:卡片表单、3、数据表格、4：页签。 暂不支持4页签
      fillOtherCellProps(pGridInfo, pGuid, pGuid+'_form', (Array.isArray(guidPanelData) ? guidPanelData?.[0] : guidPanelData) || {});
    }

		if (["3"].includes(pGridInfo?.c_type || "")) {
			for (let rIdx = 0; rIdx < (guidPanelData || [{}])?.length; rIdx++) {
				const rowData = guidPanelData?.[rIdx];
				fillOtherCellProps(pGridInfo, pGuid, pGuid+'_'+rIdx, rowData || {});
			}
		}
  }
};

const fillSubCellProps = async (subKey: string, subCardFormPanel?: LowcodeGridRowColComponents, formData?: { [key: string]: any }, parentSrc?: string) => {
	if (!formData || !subCardFormPanel?.Components?.length) {
		return;
	}
	for (let fIdx = 0; fIdx < subCardFormPanel?.Components?.length; fIdx++) {
		const rowCols = subCardFormPanel?.Components[fIdx];
		for (let cfIdx = 0; cfIdx < rowCols?.length; cfIdx++) {
			if (!state.value?.subCellProps) {
				state.value.subCellProps = {};
			}
			const colField = rowCols[cfIdx];
			state.value.subCellProps[subKey+fIdx+'_'+cfIdx] = await getComponentProps({ componentType: 'EuiText', confObject: colField, dataObject: formData, parentSrc });
		}
	}
}

const getSubCardCellProps = async () => {
  const subPanelGuidAty = Object.keys(state.value?.subPanelsGridObj || {});
  if (!subPanelGuidAty?.length) {
    return;
  }
  for (let pIdx = 0; pIdx < subPanelGuidAty?.length; pIdx++) {
    const pGuid = subPanelGuidAty[pIdx];
    const otherSubCardFormPanels = state.value?.subPanelsGridObj?.[pGuid];
    const subPanelData = state.value?.PanelData?.[pGuid];
    const parentPanelGridInfo = state.value?.PanelGridObj?.[pGuid];
    const parentContainerType = parentPanelGridInfo?.c_type || "";

    if (["1", "2"].includes(parentContainerType)) {   // 容器类型，1:普通表单、2:卡片表单、3、数据表格、4：页签。 暂不支持4页签
      for (let i = 0; i < (otherSubCardFormPanels?.length || 0); i++) {
        const otherSubCardFormPanel = otherSubCardFormPanels?.[i];
        const subKey = "other_sub" + (otherSubCardFormPanel?.c_guid || "") + "form" + "_";
        await fillSubCellProps(subKey, otherSubCardFormPanel, subPanelData || {}, parentContainerType);
      }
    }

		if (["3"].includes(parentContainerType)) {
			for (let rowIdx = 0; rowIdx < ((subPanelData || [{}])?.length || 0); rowIdx++) {
				const rowData = subPanelData?.[rowIdx];
				for (let i = 0; i < (otherSubCardFormPanels?.length || 0); i++) {
					const otherSubCardFormPanel = otherSubCardFormPanels?.[i];
					const subKey = "other_sub" + (otherSubCardFormPanel?.c_guid || "") + rowIdx + "_";
					await fillSubCellProps(subKey, otherSubCardFormPanel, rowData, parentContainerType);
				}
			}
		}
  }
};

const initData = async (fetchProxy?: FetchCustomQueryProxy) => {
	await getOtherCellProps();
	await getSubCardCellProps();

	if (fetchProxy?.isOnLoad) {
		const userInfoPage = uni.createSelectorQuery().select(".lowcode-nav-bg-wrap");
		userInfoPage.boundingClientRect(rect => {
      (state.value.navWrapRect = (rect as LowcodeRect));
      const maxBasicH = state.value.systemInfo?.windowHeight;
      const maxDiffH = 130;
      const maxHeight = Math.floor(maxBasicH - (state.value?.navWrapRect?.height || 0) - maxDiffH);
      const basicPageH = Math.floor(state.value.systemInfo?.windowHeight - (state.value?.navWrapRect?.height || 0) - 120);
      state.value.createPopupStyle = { height: Math.floor(basicPageH * 0.9) + "px" };
      state.value.cntStyle = { 'max-height': maxHeight + 'px', 'overflow-y': 'auto' };
    }).exec();
	}
  console.log("CustomQuery after initData === ", props, state.value);
};

const handleLowCodePage = async (fetchProxy?: FetchCustomQueryProxy) => {
	const lowcodePage = props?.lowcodePage;
	state.value.detailMdCode = props?.detailMdCode || "";

	const enableApprove = await getRdsSysConfig("单据是否审批", props.mdInfo?.c_md_cname) === "是";
	state.value.enableApprove = enableApprove;

	const menuCFG = lowcodePage?.c_menuCFG || null;
	if (menuCFG && Array.isArray(menuCFG.menus) && menuCFG.menus.length) {
		state.value.menusCFG = menuCFG.menus.slice(0, 3);
		state.value.menusCFGMore = menuCFG.menus.slice(3)?.map(m => ({ text: m.menuTitle || "" }));
	}

  const topPanels: LowcodePagePanel[] = [];
  lowcodePage?.Panels?.forEach(panel => {
    if (panel?.c_ppanel_guid) {
			if (!state.value?.subPanelsGridObj) {
				state.value.subPanelsGridObj = {};
			}
			if (!Array.isArray(state.value?.subPanelsGridObj[panel.c_ppanel_guid])) {
				state.value.subPanelsGridObj[panel.c_ppanel_guid] = [];
			}
			state.value.subPanelsGridObj[panel.c_ppanel_guid].push(({ ...panel, ...formGridSort(panel?.Components) }) as LowcodeGridRowColComponents);
		} else {
			topPanels.push(panel);
		}
  });

  topPanels?.forEach((panel, pIdx) => {
		if (!panel?.c_guid) {
			return;
		}
    if (!state?.value?.PanelObj) {
			state.value.PanelObj = {};
		}
    state.value.PanelObj[panel.c_guid] = ({ ...panel });
		if (!state?.value?.PanelGridObj) {
			state.value.PanelGridObj = {};
		}
    state.value.PanelGridObj[panel.c_guid] = ({ ...panel, ...formGridSort(panel?.Components) }) as LowcodeGridRowColComponents;
	});

  await initData(fetchProxy);
};

const handleSystemInfo = () => {
	const systemInfo = getSystemInfo();
	state.value.systemInfo = systemInfo;
};

onLoad(async (proxy) => {
	console.log("CustomQuery onLoad proxy ", proxy, props);

  state.value.mdCode = props?.lowcodePage?.c_lowcode_guid || "";
  state.value.mdInfo = props.mdInfo;
	state.value.pageTitle = props?.lowcodePage?.c_name ||  "自定义查询";

	await initRdsDict();
  handleSystemInfo();
	await handleLowCodePage({ isOnLoad: true });
});

</script>

<style scoped lang="scss">
@import '@/main.scss';
@import "../index.scss";
@import "./index.scss";
</style>
